package com.example.jetpackcomposelearning.viewModel

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject


@HiltViewModel
class ImagePickerViewModel @Inject constructor(@ApplicationContext private val applicationContext: Context) : ViewModel() {

    private val _imageList = MutableStateFlow<List<String>>(emptyList())
    val imageList: StateFlow<List<String>> get() = _imageList

    private val _selectedImagePath = MutableStateFlow<String?>(null)
    val selectedImagePath: StateFlow<String?> get() = _selectedImagePath

    private val _isComposeDialogVisible = MutableStateFlow(false)
    val isComposeDialogVisible: StateFlow<Boolean> get() = _isComposeDialogVisible

    private val _fileTitle = MutableStateFlow("")
    val fileTitle: StateFlow<String> get() = _fileTitle

    fun saveSelectedImages(imagePaths: List<String>) {
        viewModelScope.launch {
            _imageList.value = imagePaths
        }
    }

    fun selectImage(path: String) {
        viewModelScope.launch {
            val currentImages = _imageList.value.toMutableList()
            if (!currentImages.contains(path)) {
                currentImages.add(path)
                _imageList.value = currentImages
            }
            _selectedImagePath.value = path  // 确保每次点击都更新 selectedImagePath
        }
    }

    fun clearSelection() {
        viewModelScope.launch {
            _imageList.value = emptyList()
            _selectedImagePath.value = null
        }
    }

    fun showComposeDialog() {
        _isComposeDialogVisible.value = true
    }

    fun hideComposeDialog() {
        _isComposeDialogVisible.value = false
    }

    fun setFileTitle(title: String) {
        _fileTitle.value = title
    }

    fun getCombineVideoTitle():String{
        hideComposeDialog()
        return _fileTitle.value
    }

    fun getCombineImageList(): List<String>{
        return _imageList.value.toList()
    }

}